/*使用ssh私钥的方式管理git*/
package main

import (
	"fmt"
	"golang.org/x/crypto/ssh"
	"gopkg.in/src-d/go-git.v4"
	gitssh "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
	"io/ioutil"
	"os"
)

func main() {
	url := "git@gitee.com:bzsometest/git-test.git"
	auth := getAuth()
	if auth == nil {
		return
	}

	_, err := git.PlainClone("file/git-test", false, &git.CloneOptions{
		URL:      url,
		Progress: os.Stdout,
		Auth:     auth,
	})
	if err != nil {
		fmt.Println(err)
	}
}

func getAuth() *gitssh.PublicKeys {
	sshKey, err := ioutil.ReadFile("id_rsa")
	if err != nil {
		fmt.Println(err)
	}
	//方式1,password指生成秘钥时指定的密码
	auth, keyError := gitssh.NewPublicKeys("git", sshKey, "")
	if keyError != nil {
		fmt.Println(keyError)
	}
	//这个必须指定
	auth.HostKeyCallback, _ = gitssh.NewKnownHostsCallback("known_hosts")
	return auth
}

func getAuth02() *gitssh.PublicKeys {
	sshKey, err := ioutil.ReadFile("id_rsa")
	if err != nil {
		fmt.Println(err)
	}
	//方式2
	signer, _ := ssh.ParsePrivateKey(sshKey)
	auth := &gitssh.PublicKeys{User: "git", Signer: signer}
	auth.HostKeyCallback, _ = gitssh.NewKnownHostsCallback("known_hosts")
	return auth
}
